﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SampleSite.Models;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using Utility;

namespace SampleSite.DataAccess
{
	public class UserInfoDA
	{
		public UserInfo GetUserInfoByUsername(string username, out string error)
		{
			Database db = DatabaseFactory.CreateDatabase();
			string sqlCommand = "SELECT * FROM UserInfo WHERE UserName = @UserName";
			DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
			db.AddInParameter(dbCommand, "UserName", DbType.String, username);
			try
			{
				error = string.Empty;
				IDataReader reader = db.ExecuteReader(dbCommand);
				UserInfo user = DataHelper.FillSinger<UserInfo>(reader);
				reader.Close();
				return user;
			}
			catch (Exception ex)
			{
				error = "系统错误";
				new ExceptionLogDA().AddExceptionLog(ex.Message, ex.Source, ex.StackTrace, "UserInfoDA.GetUserInfoByUsername");
				return null;
			}

		}

		public bool CheckUserPassword(string username, string password, out string error)
		{
			UserInfo user = GetUserInfoByUsername(username, out error);
			if (user == null) return false;
			else return HashHelper.CompareHash(password, user.Password);
		}


		public bool CreateUser(string username, string password, string email, out string error)
		{
			Database db = DatabaseFactory.CreateDatabase();
			string sqlCommand = "INSERT INTO UserInfo (UserName,Email,Password,RegistIP) VALUES (@UserName,@Email,@Password,@RegistIP)";
			DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
			db.AddInParameter(dbCommand, "@UserName", DbType.String, username);
			db.AddInParameter(dbCommand, "@Password", DbType.String, HashHelper.CreateHash(password));
			db.AddInParameter(dbCommand, "@Email", DbType.String, email);
			db.AddInParameter(dbCommand, "@RegistIP", DbType.String, HttpContext.Current.Request.UserHostAddress);
			try
			{
				error = string.Empty;
				int r = (int)db.ExecuteNonQuery(dbCommand);
				return r == 1;
			}
			catch (Exception ex)
			{
				error = "系统错误";
				new ExceptionLogDA().AddExceptionLog(ex.Message, ex.Source, ex.StackTrace, "UserInfoDA.CreateUserInfo");
				return false;
			}
		}
	}
}
